<script setup lang="ts">
import { ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { Arrow } from '@/iconpark'

let contentRef = ref<null | HTMLElement>(null)
let isOpen = ref<boolean>(false)
const emit = defineEmits(['onToggle'])
const { locale } = useI18n()

function onOpenOrClose() {
  isOpen.value = !isOpen.value
  if (contentRef.value) {
    let height = contentRef.value.scrollHeight + 1
    if (isOpen.value) {
      contentRef.value.style.height = Math.ceil(height) + 'px'
    } else {
      contentRef.value.style.height = '0px'
    }
  }
  emit('onToggle', isOpen.value)
}

watch(
  () => locale.value,
  () => {
    if (contentRef.value) {
      isOpen.value = false
      contentRef.value.style.height = '0px'
    }
  }
)
</script>

<template>
  <div class="accordion-container">
    <header class="header-box" @click="onOpenOrClose">
      <div class="user-header">
        <slot name="header" />
      </div>
      <Arrow class="icon" :class="{ rotate: isOpen }" />
    </header>
    <div class="content-box" ref="contentRef">
      <slot name="default" />
    </div>
  </div>
</template>

<style scoped lang="scss">
.accordion-container {
  box-shadow: 0 0 5px 0 var(--shadow-color);
  border-radius: 5px;
  margin: 5px 0;
  .header-box {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 8px 12px;
    .user-header {
      flex: 1;
    }
    .icon {
      transform: rotate(-90deg);
      transition: all 0.3s;
      cursor: pointer;

      &.rotate {
        transform: rotate(0deg);
      }
    }
  }

  .content-box {
    transition: all 0.3s;
    transform-origin: top;
    height: 0;
    overflow: hidden;
  }
}
</style>
